<script setup>
import api from '../../api'
const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  rootForm: { type: Object, default: () => ({}) },
  options: { type: Object, default: () => ({}) },
  disabled: Boolean
})

const emit = defineEmits(['update:modelValue'])
const bankOptions = ref([])
api.getBank().then(res => {
  bankOptions.value = res.data.map(d => ({ label: d.bank_name, value: d.sb_id }))
})
// 表单处理
const formRef = ref()
const form = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

const validate = async () => {
  return new Promise(resolve => {
    formRef?.value.validate((valid, fields) => {
      resolve({ model: 'finance', name: '财务信息', success: valid, message: fields })
    })
  })
}

const typeIs1 = ref(false)
watch(
  () => props.rootForm.purchase.purchase_type,
  (type) => {
    typeIs1.value = type === 1
    if (type === 1) {
      form.value.invoice.is_invoice = 2
    }
  }
)

watch(
  () => form.value.invoice.is_invoice,
  (val) => {
    if (val === 2) {
      form.value.invoice.finance_tax = 0
      form.value.invoice.supplier_tax_rate = 0
    } else {
      form.value.invoice.finance_tax = 13
      form.value.invoice.supplier_tax_rate = 0
    }
  }
)

// 收款账户信息
const addRow = () => {
  form.value.collect.push({
    sc_id: 0,
    account_type: 1,
    bank_id: 0,
    payee: '',
    id_card: '',
    bank_address: '',
    bank_card: '',
    currency: 'CNY',
    tax_account: 1,
    default_account: 2,
  })
}

const rowDisabled = (row) => {
  return row.default_account !== 1 && form.value.collect.some(d => d.account_type === row.account_type && d.default_account === 1)
}
const handleCheck = (rowIndex) => {
  form.value.collect.forEach((d, i) => {
    if (rowIndex === i) return
    d.default_account = 2
  })
}


const collectValidator = (rule, value, cb) => {
  const { purchase_type } = props.rootForm.purchase
  if (purchase_type && purchase_type !== 1 && !value?.length) {
    cb(new Error('收款账户信息不能为空'))
  }
  cb()
}

const clearValidate = () => {
  formRef?.value?.clearValidate()
}
const resetFields = () => {
  formRef?.value?.resetFields()
}
defineExpose({ validate, clearValidate, resetFields, formRef })
</script>

<template>
  <el-form ref="formRef" :model="form" label-position="top" :disabled="disabled" :label-width="170">
    <div class="v-title mb-3">财务信息</div>
    <div class="grid grid-cols-3 gap-x-3">
      <el-form-item label="结算方式" prop="finance.period_id" :rules="[{ required: true, message: '结算方式不能为空', trigger: 'change' }]">
        <VSelect v-model="form.finance.period_id" type="period" placeholder="请选择" filterable clearable class="w-full" />
      </el-form-item>
      <el-form-item label="付款方式" prop="finance.payment_type" :rules="[{ required: true, message: '付款方式不能为空', trigger: 'change' }]">
        <VSelect v-model="form.finance.payment_type" :options="options.payment_type" placeholder="请选择" filterable clearable class="w-full" />
      </el-form-item>
      <!-- <el-form-item label="结算时间" prop="finance.settlement_time">
        <VSelect v-model="form.finance.settlement_time" :options="options.settlement_time" placeholder="请选择" filterable
          clearable class="w-full" />
      </el-form-item>
      <el-form-item label="结算日期/天数">
        <el-input-number v-model="form.finance.settlement_day" placeholder="结算日期/天数" controls-position="right" :min="0"
          :step="1" :precision="0" class="w-full" />
      </el-form-item> -->
      <el-form-item label="是否包邮">
        <v-group class="grid grid-cols-3 w-full">
          <VSelect v-model="form.finance.free_shipping" select :options="options.free_shipping" placeholder="是否包邮"
            @change="form.finance.cod_type = form.finance.free_shipping === 2 ? 2 : undefined" />
          <VSelect v-model="form.finance.cod_type" select :options="options.cod_type" placeholder="是否到付款" />
          <el-input-number v-if="form.finance.free_shipping === 3" v-model="form.finance.free_amount" controls-position="right" :min="0" :step="0.01" placeholder="请填写金额"
            :precision="2" class="w-full" />
        </v-group>
      </el-form-item>
    </div>

    <div class="mt-3 mb-5">
      <el-form-item prop="collect" :rules="[{ validator: collectValidator }]" class="mb-0 -mt-1">
        <template #label>
          <span class="v-title my-3">
            <span v-if="rootForm.purchase.purchase_type && rootForm.purchase.purchase_type !== 1" class="text-red-600 mr-1">*</span>收款账户信息
          </span>
          <el-button link type="primary" class="float-right -mr-3" @click="addRow">添加</el-button>
        </template>
        <div class="w-full">
          <vxe-table :data="form.collect">
            <vxe-column field="account_type" title="账户类型" :min-width="140">
              <template #default="{ row }">
                <el-radio-group v-model="row.account_type" @change="row.default_account = 2">
                  <el-radio :value="1" class="m-0">对公</el-radio>
                  <el-radio :value="2" class="ml-2 mr-0">对私</el-radio>
                </el-radio-group>
              </template>
            </vxe-column>
            <vxe-column field="default_account" title="默认收款账户" :min-width="110">
              <template #default="{ row }">
                <el-checkbox v-model="row.default_account" :true-value="1" :false-value="2" :disabled="rowDisabled(row)">默认</el-checkbox>
              </template>
            </vxe-column>
            <vxe-column field="bank_name" title="银行名称" :min-width="180">
              <template #default="{ row }">
                <VSelect v-model="row.bank_id" :options="bankOptions" select placeholder="请选择" filterable clearable transfer class="w-full" />
              </template>
            </vxe-column>
            <vxe-column field="payee" title="账户名称" :min-width="140">
              <template #default="{ row }">
                <el-input v-model="row.payee" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="id_card" title="身份证号码(对私)" :min-width="180">
              <template #default="{ row }">
                <el-input v-model="row.id_card" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="bank_address" title="支行名称/银行地址" :min-width="180">
              <template #default="{ row }">
                <el-input v-model="row.bank_address" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="bank_card" title="银行账号" :min-width="160">
              <template #default="{ row }">
                <el-input v-model="row.bank_card" placeholder="请输入" />
              </template>
            </vxe-column>
            <vxe-column field="currency" title="结算货币" :min-width="160">
              <template #default="{ row }">
                <VSelect v-model="row.currency" :options="options.currency" select placeholder="请选择" transfer class="w-full" />
              </template>
            </vxe-column>
            <vxe-column field="tax_account" title="是否退税账户" :min-width="130">
              <template #default="{ row }">
                <VSelect v-model="row.tax_account" :options="options.tax_account" placeholder="请选择" transfer class="w-full" />
              </template>
            </vxe-column>
            <vxe-column field="name" title="操作" fixed="right" :min-width="80">
              <template #default="{ rowIndex }">
                <el-button link type="danger" v-show="form.collect.length > 1" @click="form.collect.splice(rowIndex, 1)">删除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </el-form-item>
    </div>

    <div class="v-title my-3">开票设置</div>
    <div class="grid grid-cols-2 gap-x-3">
      <el-form-item label="是否开票" prop="invoice.is_invoice" :rules="[{ required: true, message: '是否开票不能为空', trigger: 'change' }]">
        <el-radio-group v-model="form.invoice.is_invoice" class="ml-4" :disabled="typeIs1" @change="validate">
          <el-radio :value="1">是</el-radio>
          <el-radio :value="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="开票类型" prop="invoice.invoice_type" :rules="[{ required: form.invoice.is_invoice === 1, message: '开票类型不能为空', trigger: 'change' }]">
        <VSelect v-model="form.invoice.invoice_type" :options="options.invoice_type" placeholder="请选择" filterable clearable class="w-full" />
      </el-form-item>
      <el-form-item label="开票人资质" prop="invoice.invoice_person_seniority" :rules="[{ required: form.invoice.is_invoice === 1, message: '开票人资质不能为空', trigger: 'change' }]">
        <VSelect v-model="form.invoice.invoice_person_seniority" :options="options.invoice_person_seniority" placeholder="请选择" filterable clearable class="w-full" />
      </el-form-item>
      <el-form-item label="开票人类型" prop="invoice.invoice_person_type" :rules="[{ required: form.invoice.is_invoice === 1, message: '不能为空', trigger: 'change' }]">
        <VSelect v-model="form.invoice.invoice_person_type" :options="options.invoice_person_type" placeholder="请选择" filterable clearable class="w-full" />
      </el-form-item>
      <el-form-item label="开票所在地址" prop="invoice.invoice_address" :rules="[{ required: form.invoice.is_invoice === 1, message: '开票所在地址不能为空', trigger: 'change' }]">
        <el-input v-model="form.invoice.invoice_address" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="发票税点" prop="invoice.finance_tax" :rules="[{ required: form.invoice.is_invoice === 1, message: '发票税点不能为空', trigger: 'change' }]">
        <div class="grid grid-cols-5 gap-x-3">
          <div class="flex w-full gap-2 col-span-2">
            <el-input-number v-model="form.invoice.finance_tax" placeholder="请输入" controls-position="right" :min="0" :step="0.01" :precision="2" disabled
              class="w-full" />
            <span>%</span>
          </div>
          <el-checkbox v-model="form.invoice.is_finance_tax_update" :true-value="2" :false-value="1" class="col-span-3">修改审核通过后更新该供应商所有产品的发票税点</el-checkbox>
        </div>
      </el-form-item>
      <el-form-item label="供应商税点" prop="invoice.supplier_tax_rate" :rules="[{ required: form.invoice.is_invoice === 1, message: '供应商税点不能为空', trigger: 'change' }]">
        <div class="grid grid-cols-5 gap-x-3">
          <div class="flex w-full gap-2 col-span-2">
            <el-input-number v-model="form.invoice.supplier_tax_rate" placeholder="请输入" controls-position="right" :min="0" :max="13" :step="0.01" :precision="2" :disabled="form.invoice.is_invoice === 2"
              class="w-full" />
            <span>%</span>
          </div>
          <el-checkbox v-model="form.invoice.is_supplier_tax_update" :true-value="2" :false-value="1" class="col-span-3">修改审核通过后更新该供应商所有产品的供应商税点</el-checkbox>
        </div>
      </el-form-item>
      <el-form-item label="一般纳税人资质认定时间" prop="invoice.tax_time" :rules="[{ required: form.invoice.is_invoice === 1, message: '一般纳税人资质认定时间不能为空', trigger: 'change' }]">
        <el-date-picker v-model="form.invoice.tax_time" type="date" value-format="YYYY-MM-DD" placeholder="请选择" class="w-full" />
      </el-form-item>
      <el-form-item label="财务类型" prop="finance.finance_type" :rules="[{ required: form.invoice.is_invoice === 1, message: '财务类型不能为空', trigger: 'change' }]">
        <VSelect v-model="form.finance.finance_type" placeholder="请选择" :options="options.finance_type" class="w-full" />
      </el-form-item>
    </div>
  </el-form>
</template>
